package com.wx.springboot.step9back.controller;

import com.wx.springboot.step9back.common.api.CommonResult;
import com.wx.springboot.step9back.model.User;
import com.wx.springboot.step9back.service.RedisService;
import com.wx.springboot.step9back.service.UserService;
import com.wx.springboot.step9back.vo.LoginParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@RestController
@RequestMapping
public class LoginController {

    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisService redisService;

    @PostMapping("/register")
    public CommonResult register(@RequestBody User user){
        HashMap<String, String> data = new HashMap<>();
        String result = userService.register(user);
        data.put("data", result);
        return CommonResult.success(data);
    }

    @PostMapping("/login")
    public CommonResult login(@RequestBody LoginParam loginParam, HttpServletRequest request){
        HashMap<String, String> data = new HashMap<>();
        String checkCode = (String) redisService.get("checkCode");
        if (checkCode.toLowerCase() == null || !checkCode.toLowerCase().equals(loginParam.getCode().toLowerCase())){
            return CommonResult.validateFailed("验证码错误或失效");
        } else {
            String token = null;
            try {
                token = userService.login(loginParam,request);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (token == "该用户已被冻结"){
                return CommonResult.validateFailed("该用户已被冻结");
            } else {
                if (StringUtils.isEmpty(token) || token == "用户名或密码错误"){
                    return CommonResult.validateFailed("用户名或密码错误");
                } else if (token == "密码输入错误超过三次，该用户已被冻结"){
                    return CommonResult.validateFailed("密码输入错误超过三次，该用户已被冻结");
                }
                redisService.set("userCode",loginParam.getUserCode());
                data.put("tokenHead",tokenHead);
                data.put("token",token);
            }
        }
        return CommonResult.success(data);
    }

    @ApiOperation("用户登出")
    @PostMapping("/loginOut")
    public CommonResult loginOut(){
        HashMap<String, Object> data = new HashMap<>();
        Long result = redisService.del("userCode");
        data.put("result", result);
        return CommonResult.success(data);
    }

}
